package one2one;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import util.HibernateUtil;

public class TestOne2One {
	//保存User和Passport
	@Test
	public void testSave()
	{
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		
		User user = new User();
		user.setName("uuu22");
		
		Passport passport = new Passport();
		passport.setPassportNo("123456");
		
		//设置双方的关联！
		user.setPassport(passport);
		passport.setUser(user);
		
		session.save(user);  //用到级联更新
		
		tx.commit();
		
	}
	
	//通过User获取Passport
	@Test
	public void testRead()
	{
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		User user = (User)session.load(User.class, 1);
		System.out.println(user.getName());
		Passport passport = user.getPassport();
		System.out.println(passport.getId()+","+passport.getPassportNo());
		
		session.getTransaction().commit();
	}
	
	//向已有用户添加Passport
	@Test
	public void testSavePassport()
	{
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		
		User user = (User)session.load(User.class, 2);
		
		Passport passport = new Passport();
		passport.setPassportNo("88888888");
		
		//设置双方的关联！
		user.setPassport(passport);
		passport.setUser(user);
		
		
		tx.commit();
		
	}
	
	@Test//级联删除
	public void testDelete(){
		Session s = HibernateUtil.getSession();
		s.beginTransaction();
		User u= (User) s.load(User.class, 2);
		s.delete(u);
		s.getTransaction().commit();
	}
}
